import React, { useRef, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { Tooltip } from '@douyinfe/semi-ui';

const toCanvasCoords = (point, centerX, centerY, maxRadius) => {
  const { azimuth, elevation } = point;
  const radius = maxRadius * (1 - elevation / 90);
  const angleRad = (azimuth * Math.PI) / 180 - Math.PI / 2;
  const x = centerX + radius * Math.cos(angleRad);
  const y = centerY + radius * Math.sin(angleRad);
  return { x, y };
};

const Polaris = ({ data, style }) => {
  const canvasRef = useRef(null);
  const containerRef = useRef(null);
  const [size, setSize] = useState({ width: 0, height: 0 });
  const [bgGlobeImage, setBgGlobeImage] = useState(null);
  const [systemImages, setSystemImages] = useState({});
  const [dataPoints, setDataPoints] = useState([]);
  const [selectedPoint, setSelectedPoint] = useState(null);
  const [tooltipPos, setTooltipPos] = useState(null);
  // 添加新状态用于跟踪鼠标悬浮的数据点
  const [hoveredPoint, setHoveredPoint] = useState(null);

  useEffect(() => {
    const resizeObserver = new ResizeObserver(entries => {
      if (entries.length > 0) {
        const { width, height } = entries[0].contentRect;
        if (width > 0 && height > 0) {
          setSize({ width, height });
        }
      }
    });
    if (containerRef.current) {
      resizeObserver.observe(containerRef.current);
    }
    return () => resizeObserver.disconnect();
  }, []);

  useEffect(() => {
    const img = new Image();
    img.src = '/img/bg_globe.png';
    img.onload = () => setBgGlobeImage(img);
    img.onerror = () => console.error('Failed to load background globe image');
  }, []);

  useEffect(() => {
    const systems = ['bds', 'gps', 'gal', 'glonass']; // 可扩展
    const imageMap = {};
    let loadedCount = 0;

    systems.forEach(system => {
      const img = new Image();
      img.src = `/img/satellitesLogo/${system}.png`;
      img.onload = () => {
        imageMap[system] = img;
        loadedCount++;
        if (loadedCount === systems.length) {
          setSystemImages(imageMap);
        }
      };
      img.onerror = () => {
        console.error(`无法加载图标: ${system}.png`);
        loadedCount++;
        if (loadedCount === systems.length) {
          setSystemImages(imageMap);
        }
      };
    });
  }, []);

  useEffect(() => {
    const canvas = canvasRef.current;
    const { width, height } = size;
    if (!canvas || width === 0 || height === 0) return;

    const ctx = canvas.getContext('2d', { alpha: true });
    const dpr = window.devicePixelRatio || 1;
    canvas.width = width * dpr;
    canvas.height = height * dpr;
    canvas.style.width = `${width}px`;
    canvas.style.height = `${height}px`;
    ctx.scale(dpr, dpr);
    ctx.clearRect(0, 0, width, height);

    const centerX = width / 2;
    const centerY = height / 2;
    const azimuthLabelOffset = 20;
    const elevationLabelPadding = 15;
    const minOverallPadding = Math.max(azimuthLabelOffset, elevationLabelPadding) + 10;
    const maxRadius = Math.min(width, height) / 2 - minOverallPadding;
    if (maxRadius <= 0) return;

    if (bgGlobeImage) {
      const scaleFactor = 1.72;
      const bgSize = maxRadius * 2 * scaleFactor;
      ctx.drawImage(bgGlobeImage, centerX - bgSize / 2, centerY - bgSize / 2, bgSize, bgSize);
    }

    const gridColor = '#fff';
    const textColor = '#fff';
    ctx.strokeStyle = gridColor;
    ctx.fillStyle = textColor;
    ctx.font = '12px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    const elevations = [60, 30, 0];
    elevations.forEach(el => {
      const radius = maxRadius * (1 - el / 90);
      ctx.beginPath();
      ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
      ctx.stroke();
      ctx.fillText(`${el}°`, centerX, centerY - radius - (el === 0 ? elevationLabelPadding - 8 : 8));
    });
    ctx.fillText(`90°`, centerX, centerY);

    const azimuths = { N: 0, E: 90, S: 180, W: 270 };
    Object.entries(azimuths).forEach(([label, angle]) => {
      const { x, y } = toCanvasCoords({ azimuth: angle, elevation: 0 }, centerX, centerY, maxRadius);
      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      ctx.lineTo(x, y);
      ctx.stroke();

      const angleRad = (angle * Math.PI) / 180 - Math.PI / 2;
      const labelX = centerX + (maxRadius + azimuthLabelOffset) * Math.cos(angleRad);
      const labelY = centerY + (maxRadius + azimuthLabelOffset) * Math.sin(angleRad);
      ctx.fillText(label, labelX, labelY);
    });

    ctx.fillStyle = 'var(--semi-color-primary)';
    const pointsOnCanvas = [];

    // 首先绘制非悬浮状态的数据点
    data.forEach(point => {
      if (point.elevation < 0 || point.elevation > 90) return;
      const { x, y } = toCanvasCoords(point, centerX, centerY, maxRadius);
      pointsOnCanvas.push({ ...point, x, y });

      // 如果是悬浮点，则先跳过绘制，最后单独绘制以确保在顶层
      if (hoveredPoint && hoveredPoint.id === point.id && hoveredPoint.system === point.system) {
        return;
      }

      const img = systemImages[point.system?.toLowerCase()];
      if (img) {
        const imgSize = 35;
        ctx.drawImage(img, x - imgSize / 2, y - imgSize / 2, imgSize, imgSize);
        ctx.fillStyle = 'white';
        ctx.font = 'bold 15px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(point.id, x, y);
        ctx.fillStyle = 'var(--semi-color-primary)';
      } else {
        ctx.beginPath();
        ctx.arc(x, y, 5, 0, 2 * Math.PI);
        ctx.fill();
      }
    });

    // 最后绘制悬浮状态的数据点，确保在顶层
    if (hoveredPoint) {
      const { x, y } = toCanvasCoords(hoveredPoint, centerX, centerY, maxRadius);
      const img = systemImages[hoveredPoint.system?.toLowerCase()];
      if (img) {
        // 悬浮时缩放125%
        const imgSize = 35 * 1.25;
        ctx.drawImage(img, x - imgSize / 2, y - imgSize / 2, imgSize, imgSize);
        ctx.fillStyle = 'white';
        ctx.font = 'bold 18.75px Arial'; // 字体也相应缩放
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(hoveredPoint.id, x, y);
        ctx.fillStyle = 'var(--semi-color-primary)';
      } else {
        // 对于没有图标的点，悬浮时也放大
        ctx.beginPath();
        ctx.arc(x, y, 6.25, 0, 2 * Math.PI);
        ctx.fill();
      }
    }

    setDataPoints(pointsOnCanvas);
  }, [data, size, bgGlobeImage, systemImages, hoveredPoint]);

  const handleMouseMove = (e) => {
    if (!canvasRef.current) return;
    const rect = canvasRef.current.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    const hovered = dataPoints.find(point => {
      const dx = mouseX - point.x;
      const dy = mouseY - point.y;
      return Math.sqrt(dx * dx + dy * dy) < 10;
    });
    
    if (hovered) {
      setHoveredPoint(hovered);
    } else {
      setHoveredPoint(null);
      setTooltipPos(null);
    }
  };

  const handleClick = (e) => {
    if (!canvasRef.current) return;
    const rect = canvasRef.current.getBoundingClientRect();
    const mouseX = e.clientX - rect.left;
    const mouseY = e.clientY - rect.top;

    const clicked = dataPoints.find(point => {
      const dx = mouseX - point.x;
      const dy = mouseY - point.y;
      return Math.sqrt(dx * dx + dy * dy) < 10;
    });

    if (clicked) {
      setSelectedPoint(clicked);
      setTooltipPos({ x: clicked.x, y: clicked.y });
    } else {
      setSelectedPoint(null);
      setTooltipPos(null);
    }
  };

  return (
    <div
      ref={containerRef}
      style={{
        ...style,
        position: 'relative',
        width: '100%',
        height: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      }}
    >
      <canvas
        ref={canvasRef}
        onMouseMove={handleMouseMove}
        onClick={handleClick}
        style={{ display: 'block' }}
      />
      {selectedPoint && tooltipPos && (
        <Tooltip
          visible
          content={
            <div style={{ maxWidth: 200 }}>
              <div><strong>系统:</strong> {selectedPoint.system}</div>
              <div><strong>PRN:</strong> {selectedPoint.id}</div>
              <div><strong>方位角:</strong> {selectedPoint.azimuth}°</div>
              <div><strong>仰角:</strong> {selectedPoint.elevation}°</div>
            </div>
          }
          position="top"
          trigger="custom"
        >
          <div
            style={{
              position: 'absolute',
              left: tooltipPos.x,
              top: tooltipPos.y,
              transform: 'translate(-50%, -100%)',
              pointerEvents: 'none',
              zIndex: 1000,
            }}
          >
            <div style={{ width: 1, height: 1 }} />
          </div>
        </Tooltip>
      )}
    </div>
  );
};

Polaris.propTypes = {
  data: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
    azimuth: PropTypes.number.isRequired,
    elevation: PropTypes.number.isRequired,
    system: PropTypes.string.isRequired,
  })),
  style: PropTypes.object,
};

Polaris.defaultProps = {
  data: [],
  style: {},
};

export default Polaris;
